import 'package:flutter_douban/main_page/class/model/class_item_model.dart';
import 'package:sqflite/sqlite_api.dart';
import 'base_db_provider.dart';

class ClassDbProvider extends BaseDbProvider {
  /// 表名
  final String name = 'ClassInfo';

  /// 课程id
  final String Id = "id";

  /// 图片链接
  final String i = "i";

  /// 老师名字
  final String un = "un";

  /// 课程描述
  final String t = "t";

  /// 课程参加人数
  final String ec = "ec";

  /// 收藏用户电话
  final String phoneNum = "phoneNum";

  /// 收藏时间
  final String time = "time";

  ClassDbProvider();
  @override
  tableName() {
    return name;
  }

  /// 创建表
  @override
  createTableString() {
    return '''
        create table $name (
        $Id integer primary key,$i text not null,
        $un text not null,$t text not null,$ec int not null,$phoneNum text not null,$time bigint)
      ''';
  }

  /// 查询数据库
  Future _getClassProvider(Database db, int id,String phone) async {
    List<Map<String, dynamic>> maps =
        await db.rawQuery("select * from $name where $Id = $id AND $phoneNum = $phone");
    return maps;
  }

  /// 插入到数据库
  Future insert(ClassItemModel model,String phone) async {
    Database db = await getDataBase();
    var noteProvider = await _getClassProvider(db, int.parse(model.id!),phone);
    if (noteProvider != null) {
      /// 删除数据
      await db.delete(name, where: "$Id = ? AND $phoneNum = ?", whereArgs: [model.id,phone]);
    }
    return await db
        .rawInsert("insert into $name ($Id,$i,$un,$t,$ec,$phoneNum,$time) values (?,?,?,?,?,?,?)", [
      int.parse(model.id!),
      model.i,
      model.un,
      model.t,
      model.ec,
      phone,
      /// 当前时间戳
      DateTime.now().millisecondsSinceEpoch,
    ]);
  }

  /// 删除到数据库
  Future delete(int id,String phone) async {
    Database db = await getDataBase();
    var noteProvider = await _getClassProvider(db, id,phone);
    if (noteProvider != null) {
      /// 删除数据
      await db.delete(name, where: "$Id = ? AND $phoneNum = ?", whereArgs: [id,phone]);
    }
    return await db.rawDelete(
      "delete from $name where $Id = $id AND $phoneNum = $phone",
    );
  }

  /// 获取表中符合用户的全部数据
  Future getClassInfo(String phone) async {
    Database db = await getDataBase();
    List<Map<String, dynamic>> maps =
    await db.rawQuery("select * from $name where $phoneNum = $phone order by $time desc");
    ClassItemModelList classItemModelList = ClassItemModelList.fromJson(maps);
    return classItemModelList.list;
  }




  // /// 更新数据库
  // Future<void> update(ClassItemModel model) async {
  //   Database database = await getDataBase();
  //   await database
  //       .rawUpdate("update $name set $Id = ?,$i = ?,$un = ?,$t = ?,$ec = ?", [
  //     int.parse(model.id!),
  //     model.i,
  //     model.un,
  //     model.t,
  //     model.ec,
  //   ]);
  // }

}
